<template>
  <div class="yitoujianli-page">
    <!-- 标题栏 -->
    <van-nav-bar
      title="已投简历"
      left-arrow
      @click-left="goBack"
      fixed
      placeholder
    />

    <!-- 主容器 -->
    <div class="yitoujianli-container">
      <!-- 侧边导航栏 -->
      <van-sidebar
        v-model="activeKey"
        @change="onSidebarChange"
        class="sidebar"
      >
        <van-sidebar-item title="删除已投简历" />
        <van-sidebar-item title="投递简历" />
        <van-sidebar-item title="已投简历列表" />
      </van-sidebar>

      <!-- 内容区域 -->
      <div class="content">
        <!-- 删除已投简历 -->
        <div v-if="activeKey === 0" class="delete-delivery-section">
          <div class="section-title">删除已投简历</div>

          <!-- 搜索框 -->
          <div class="search-box">
            <van-field
              v-model="deleteSearchKeyword"
              placeholder="请输入简历ID或关键词搜索"
              clearable
              @keyup.enter="searchDeleteResumes"
            >
              <template #button>
                <van-button
                  type="primary"
                  size="small"
                  @click="searchDeleteResumes"
                  :loading="deleteSearchLoading"
                >
                  搜索
                </van-button>
              </template>
            </van-field>
          </div>

          <!-- 已投简历列表 -->
          <div class="resume-list">
            <van-list
              v-model:loading="deleteLoading"
              :finished="deleteFinished"
              finished-text="没有更多了"
              @load="loadDeleteResumes"
            >
              <van-cell
                v-for="item in deleteResumeList"
                :key="item.id"
                :title="item.title || '简历标题'"
                :label="`投递时间: ${formatDate(item.createdAt)}`"
                is-link
                @click="showDeleteDetail(item)"
              >
                <template #right-icon>
                  <van-button
                    type="danger"
                    size="small"
                    @click.stop="deleteDeliveryResume(item)"
                    :loading="item.deleting"
                  >
                    删除
                  </van-button>
                </template>
              </van-cell>
            </van-list>
          </div>

          <!-- 已投简历详情弹窗 -->
          <van-popup
            v-model:show="showDeleteDetailPopup"
            position="bottom"
            :style="{ height: '60%' }"
            round
          >
            <div class="detail-content">
              <div class="detail-header">
                <h3>已投简历详情</h3>
                <van-icon name="cross" @click="closeDeleteDetail" />
              </div>
              <div class="detail-body">
                <div v-if="selectedDeleteResume">
                  <p>
                    <strong>简历标题:</strong>
                    {{ selectedDeleteResume.title }}
                  </p>
                  <p>
                    <strong>投递时间:</strong>
                    {{ formatDate(selectedDeleteResume.createdAt) }}
                  </p>
                  <p>
                    <strong>简历描述:</strong>
                    {{ selectedDeleteResume.description || "暂无描述" }}
                  </p>
                </div>
              </div>
            </div>
          </van-popup>
        </div>

        <!-- 投递简历 -->
        <div v-else-if="activeKey === 1" class="post-resume-section">
          <div class="section-title">投递简历</div>

          <van-form @submit="submitPostResume">
            <van-field
              v-model="postResume.title"
              name="title"
              label="简历标题"
              placeholder="请输入简历标题"
              :rules="[{ required: true, message: '请输入简历标题' }]"
            />

            <van-field
              v-model="postResume.description"
              name="description"
              label="简历描述"
              type="textarea"
              placeholder="请输入简历描述"
              rows="3"
              :rules="[{ required: true, message: '请输入简历描述' }]"
            />

            <van-field
              v-model="postResume.content"
              name="content"
              label="简历内容"
              type="textarea"
              placeholder="请输入简历详细内容"
              rows="6"
              :rules="[{ required: true, message: '请输入简历内容' }]"
            />

            <van-field
              v-model="postResume.companyId"
              name="companyId"
              label="公司ID"
              placeholder="请输入目标公司ID"
              :rules="[{ required: true, message: '请输入公司ID' }]"
            />

            <div style="margin: 16px">
              <van-button
                round
                block
                type="primary"
                native-type="submit"
                :loading="postSubmitLoading"
              >
                投递简历
              </van-button>
            </div>
          </van-form>
        </div>

        <!-- 已投简历列表 -->
        <div v-else-if="activeKey === 2" class="delivery-list-section">
          <div class="section-title">已投简历列表</div>

          <!-- 搜索框 -->
          <div class="search-box">
            <van-field
              v-model="deliveryListSearchKeyword"
              placeholder="请输入关键词搜索已投简历"
              clearable
              @keyup.enter="searchDeliveryList"
            >
              <template #button>
                <van-button
                  type="primary"
                  size="small"
                  @click="searchDeliveryList"
                  :loading="deliveryListSearchLoading"
                >
                  搜索
                </van-button>
              </template>
            </van-field>
          </div>

          <!-- 已投简历列表 -->
          <div class="resume-list">
            <van-list
              v-model:loading="deliveryListLoading"
              :finished="deliveryListFinished"
              finished-text="没有更多了"
              @load="loadDeliveryList"
            >
              <van-cell
                v-for="item in deliveryList"
                :key="item.id"
                :title="item.title"
                :label="`投递时间: ${formatDate(item.createdAt)}`"
                is-link
                @click="showDeliveryListDetail(item)"
              />
            </van-list>
          </div>

          <!-- 已投简历详情弹窗 -->
          <van-popup
            v-model:show="showDeliveryListDetailPopup"
            position="bottom"
            :style="{ height: '70%' }"
            round
          >
            <div class="detail-content">
              <div class="detail-header">
                <h3>已投简历详情</h3>
                <van-icon name="cross" @click="closeDeliveryListDetail" />
              </div>
              <div class="detail-body">
                <div v-if="selectedDeliveryListResume">
                  <p><strong>简历标题:</strong> {{ selectedDeliveryListResume.title }}</p>
                  <p>
                    <strong>投递时间:</strong>
                    {{ formatDate(selectedDeliveryListResume.createdAt) }}
                  </p>
                  <p>
                    <strong>简历描述:</strong> {{ selectedDeliveryListResume.description }}
                  </p>
                  <p><strong>简历内容:</strong></p>
                  <div class="resume-content">{{ selectedDeliveryListResume.content }}</div>
                </div>
              </div>
            </div>
          </van-popup>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import {
  NavBar,
  Sidebar,
  SidebarItem,
  List,
  Cell,
  Popup,
  Icon,
  Toast,
  Field,
  Button,
  Form,
  Dialog,
} from "vant";
import httpd from "../../utils/httpd.js";

const router = useRouter();

// 侧边栏状态
const activeKey = ref(0);

// 删除已投简历相关
const deleteSearchKeyword = ref("");
const deleteSearchLoading = ref(false);
const deleteResumeList = ref([]);
const deleteLoading = ref(false);
const deleteFinished = ref(false);
const showDeleteDetailPopup = ref(false);
const selectedDeleteResume = ref(null);

// 投递简历相关
const postResume = ref({
  title: "",
  description: "",
  content: "",
  companyId: "",
});
const postSubmitLoading = ref(false);

// 已投简历列表相关
const deliveryListSearchKeyword = ref("");
const deliveryListSearchLoading = ref(false);
const deliveryList = ref([]);
const deliveryListLoading = ref(false);
const deliveryListFinished = ref(false);
const showDeliveryListDetailPopup = ref(false);
const selectedDeliveryListResume = ref(null);

// 返回上一页
const goBack = () => {
  router.back();
};

// 侧边栏切换
const onSidebarChange = (index) => {
  activeKey.value = index;
  if (index === 0 && deleteResumeList.value.length === 0) {
    loadDeleteResumes();
  } else if (index === 2 && deliveryList.value.length === 0) {
    loadDeliveryList();
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleDateString("zh-CN");
};

// ========== 删除已投简历功能 ==========
const searchDeleteResumes = async () => {
  deleteSearchLoading.value = true;
  try {
    const response = await httpd.get("/api/v1/company/delivery-company-resume-delete", {
      params: { keyword: deleteSearchKeyword.value },
    });
    if (response.status === 200) {
      deleteResumeList.value = response.data.list || [];
      Toast.success("搜索成功");
    } else {
      Toast.fail(response.message || "搜索失败");
    }
  } catch (error) {
    console.error("搜索已投简历失败:", error);
    Toast.fail("网络错误，请稍后重试");
  } finally {
    deleteSearchLoading.value = false;
  }
};

const loadDeleteResumes = async () => {
  deleteLoading.value = true;
  try {
    const response = await httpd.get("/api/v1/company/delivery-company-resume-delete");
    if (response.status === 200) {
      deleteResumeList.value = response.data.list || [];
      deleteFinished.value = true;
    } else {
      Toast.fail(response.message || "获取已投简历列表失败");
    }
  } catch (error) {
    console.error("获取已投简历列表失败:", error);
    Toast.fail("网络错误，请稍后重试");
  } finally {
    deleteLoading.value = false;
  }
};

const deleteDeliveryResume = async (item) => {
  if (!item.deleting) item.deleting = false;
  try {
    await Dialog.confirm({
      title: "确认删除",
      message: `确定要删除已投简历"${item.title}"吗？`,
    });

    item.deleting = true;
    const response = await httpd.delete(
      `/api/v1/company/delivery-company-resume-delete/${item.id}`
    );
    if (response.status === 200) {
      Toast.success("删除成功");
      // 从列表中移除
      const index = deleteResumeList.value.findIndex(
        (resume) => resume.id === item.id
      );
      if (index > -1) {
        deleteResumeList.value.splice(index, 1);
      }
    } else {
      Toast.fail(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除已投简历失败:", error);
      Toast.fail("网络错误，请稍后重试");
    }
  } finally {
    item.deleting = false;
  }
};

const showDeleteDetail = (item) => {
  selectedDeleteResume.value = item;
  showDeleteDetailPopup.value = true;
};

const closeDeleteDetail = () => {
  showDeleteDetailPopup.value = false;
  selectedDeleteResume.value = null;
};

// ========== 投递简历功能 ==========
const submitPostResume = async (values) => {
  postSubmitLoading.value = true;
  try {
    const response = await httpd.post(
      "/api/v1/company/company-resume-post",
      values
    );
    if (response.status === 200) {
      Toast.success("简历投递成功");
      // 重置表单
      postResume.value = {
        title: "",
        description: "",
        content: "",
        companyId: "",
      };
    } else {
      Toast.fail(response.message || "简历投递失败");
    }
  } catch (error) {
    console.error("投递简历失败:", error);
    Toast.fail("网络错误，请稍后重试");
  } finally {
    postSubmitLoading.value = false;
  }
};

// ========== 已投简历列表功能 ==========
const searchDeliveryList = async () => {
  deliveryListSearchLoading.value = true;
  try {
    const response = await httpd.get("/api/v1/company/company-resume-post-list", {
      params: { keyword: deliveryListSearchKeyword.value },
    });
    if (response.status === 200) {
      deliveryList.value = response.data.list || [];
      Toast.success("搜索成功");
    } else {
      Toast.fail(response.message || "搜索失败");
    }
  } catch (error) {
    console.error("搜索已投简历列表失败:", error);
    Toast.fail("网络错误，请稍后重试");
  } finally {
    deliveryListSearchLoading.value = false;
  }
};

const loadDeliveryList = async () => {
  deliveryListLoading.value = true;
  try {
    const response = await httpd.get("/api/v1/company/company-resume-post-list");
    if (response.status === 200) {
      deliveryList.value = response.data.list || [];
      deliveryListFinished.value = true;
    } else {
      Toast.fail(response.message || "获取已投简历列表失败");
    }
  } catch (error) {
    console.error("获取已投简历列表失败:", error);
    Toast.fail("网络错误，请稍后重试");
  } finally {
    deliveryListLoading.value = false;
  }
};

const showDeliveryListDetail = (item) => {
  selectedDeliveryListResume.value = item;
  showDeliveryListDetailPopup.value = true;
};

const closeDeliveryListDetail = () => {
  showDeliveryListDetailPopup.value = false;
  selectedDeliveryListResume.value = null;
};

onMounted(() => {
  // 默认加载删除已投简历列表
  loadDeleteResumes();
});
</script>

<style scoped lang="less">
.yitoujianli-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.yitoujianli-container {
  display: flex;
  height: calc(100vh - 46px);
}

.sidebar {
  width: 100px;
  background: #fff;
  border-right: 1px solid #ebedf0;
}

.content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 16px;
  padding-left: 8px;
}

.search-box {
  margin-bottom: 16px;
}

.resume-list {
  .van-cell {
    margin-bottom: 8px;
    border-radius: 8px;
    background: #fff;
  }
}

// 投递简历模块样式
.post-resume-section {
  .van-form {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
  }
}

.detail-content {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebedf0;

  h3 {
    font-size: 18px;
    font-weight: 600;
    color: #323233;
    margin: 0;
  }

  .van-icon {
    font-size: 20px;
    color: #969799;
    cursor: pointer;
  }
}

.detail-body {
  flex: 1;
  line-height: 1.6;
  color: #666;
  font-size: 14px;
  overflow-y: auto;

  p {
    margin-bottom: 12px;
  }

  .resume-content {
    background: #f7f8fa;
    padding: 12px;
    border-radius: 6px;
    margin-top: 8px;
    white-space: pre-wrap;
  }
}

// 深度样式
:deep(.van-sidebar-item) {
  font-size: 14px;
}

:deep(.van-sidebar-item--selected) {
  background: #e8f5e8;
  color: #6fb06c;
}

:deep(.van-field__label) {
  color: #323233;
  font-weight: 500;
}

:deep(.van-button--danger) {
  background: #ee0a24;
  border-color: #ee0a24;
}
</style>